package com.wxh.bomb.httpserver.server;

import com.wxh.bomb.httpserver.utils.CloseUtil;

import java.io.IOException;
import java.net.Socket;

/**
 * 一个请求和转发就是一个对象
 * @className Dispatcher
 * @date 2015年12月4日 下午2:21:49
 * @author <a href="mailto:waferslove@sina.com">王星火</a>
 * @version V1.0
 */
public class Dispatcher implements Runnable{
	private Socket client;
	private Request req;
	private Response rep;
	private int code = 200;
	
	public Dispatcher(Socket client){
		this.client = client;
		req = new Request(client);
		rep = new Response(client);
	}

	@Override
	public void run() {
		try {
			Servlet serv = WebApp.getServlet(req.getUrl());
			if (null == serv) {
				// 找不到
				code = 404;
			} else {
				serv.service(req, rep);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} 				
		try {
			rep.pushToClient(code); //推送到客户端
		} catch (IOException e) {
			try {
				rep.pushToClient(500);
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		}
		// 关闭连接
		CloseUtil.closeSocket(client);
	}
	

}
